package com.xbongbong.pro.aiassistant.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.help.UserAndDepartmentHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.pro.aiassistant.abstracts.AbstractAiAssistantStrategyHandle;
import com.xbongbong.pro.aiassistant.manager.feign.BusinessFeignClient;
import com.xbongbong.pro.aiassistant.service.SsMessageMergeService;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.domain.entity.AiAssistantHistoryEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.smartsettings.enums.AiAssistantPushTypeEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartActionTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.AiAssistantBaseProducer;
import com.xbongbong.pro.service.toolbox.smartsettings.help.SmartSettingsHelp;
import com.xbongbong.pro.smartsettings.pojo.SsExecutorPojo;
import com.xbongbong.pro.smartsettings.pojo.SsExecutorUserIdPojo;
import com.xbongbong.pro.smartsettings.pojo.SsMessageMergePojo;
import com.xbongbong.pro.smartsettings.pojo.dto.RunStrategyDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartStrategyRabbitMqDTO;
import com.xbongbong.pro.weblist.pojo.WorkReportUserStatisicPojo;
import com.xbongbong.pro.weblist.pojo.dto.WorkReportUserStatisicDTO;
import com.xbongbong.pro.weblist.pojo.vo.WorkReportUserStatisicVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkReportTypeEnum;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2020/09/17 15:24
 */
@Service("workReportAiAssistantStrategyHandle")
public class WorkReportAiAssistantStrategyHandle extends AbstractAiAssistantStrategyHandle implements AiAssistantStrategyHandle {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkReportAiAssistantStrategyHandle.class);

    @Resource
    private SsMessageMergeService ssMessageMergeService;
    @Resource
    private SmartSettingsHelp smartSettingsHelp;
    @Resource
    private AiAssistantBaseProducer aiAssistantBaseProducer;
    @Resource
    private BusinessFeignClient businessFeignClient;
    @Resource
    private UserAndDepartmentHelp userAndDepartmentHelp;

    @Override
    public List<SsExecutorPojo> getExecutorUserList(AiAssistantEntity aiAssistantEntity, List<Long> dataIdList, List<PaasFormDataEntityExt> formDataList) {
        List<SsExecutorPojo> ssExecutorList = new ArrayList<>();
        try {
            String corpid = aiAssistantEntity.getCorpid();
            // // 当前需要执行的人员
            SsExecutorUserIdPojo ssExecutorUserIdPojo = getExecUserIds(aiAssistantEntity);
            Set<String> execUserIds = ssExecutorUserIdPojo.getExecUserIds();
            List<ConditionsEntityExt> conditionsEntityExtList = aiAssistantEntity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
            // 当前日期，默认周报
            Integer now = DateUtil.getTodayInt();
            Integer reportType = WorkReportTypeEnum.WEEKLY.getType();

            List<UserEntity> adminList = userAndDepartmentHelp.getAdminOrBoss(corpid);
            String adminUserId = null;
            if(!adminList.isEmpty()) {
                adminUserId = adminList.get(0).getUserId();
            }
            if(adminUserId == null) {
                return new ArrayList<>();
            }
            if (!conditionsEntityExtList.isEmpty()) {
                // 获取类型，用于区分日报、月报、周报
                ConditionsEntityExt conditionsEntityExt = conditionsEntityExtList.get(0);
                reportType = conditionsEntityExt.getFieldType();
            }
            if (Objects.equals(WorkReportTypeEnum.WEEKLY.getType(), reportType)) {
                now = DateUtil.getThisWeekMorning();
            } else if (Objects.equals(WorkReportTypeEnum.MONTHLY.getType(), reportType)) {
                now = DateUtil.getFirstDateOfThisMonth();
            }
            // 工作报告日期
            String startDay = DateUtil.getDateString(now);
            String endDay = DateUtil.getDateString(now + TimeConstant.SECONDS_PER_DAY);
            JSONArray reportDateArray = new JSONArray();
            reportDateArray.add(startDay);
            reportDateArray.add(endDay);

            // 获取未写工作报告的人
            WorkReportUserStatisicDTO workReportUserStatisicDTO = new WorkReportUserStatisicDTO();
            workReportUserStatisicDTO.setCorpid(corpid);
            // 超管id
            workReportUserStatisicDTO.setUserId(adminUserId);
            workReportUserStatisicDTO.setPlatform(StringConstant.PLATFORM_WEB);
            workReportUserStatisicDTO.setPageDone(BasicConstant.ONE);
            workReportUserStatisicDTO.setPageUnDone(BasicConstant.ONE);
            workReportUserStatisicDTO.setReportType(reportType);
            workReportUserStatisicDTO.setReportDate(reportDateArray);

            Locale locale = LocaleContextHolder.getLocale();
            String lang = locale.toString();
            String userStatisticData = businessFeignClient.workReportUserStatisticsList(workReportUserStatisicDTO, lang);
            JSONObject resultObj = JsonHelperUtil.parseObject(userStatisticData);
            if (ErrorCodeEnum.API_SUCCESS.getCode() != (int)resultObj.get(StringConstant.CODE)) {
                throw new XbbException(resultObj.getIntValue(StringConstant.CODE),resultObj.getString(StringConstant.KEY_ERROR_MSG));
            }
            WorkReportUserStatisicVO userStatisicVO = JsonHelperUtil.parseObject(resultObj.getString("result"),WorkReportUserStatisicVO.class);
            List<WorkReportUserStatisicPojo> unDoneUsers = userStatisicVO.getUnDoneUsers();
            if (Objects.isNull(unDoneUsers) || unDoneUsers.isEmpty()) {
                return ssExecutorList;
            }

            // 与需要执行的人员取交集
            if (!execUserIds.isEmpty()) {
                Iterator<WorkReportUserStatisicPojo> iterator = unDoneUsers.iterator();
                while (iterator.hasNext()) {
                    WorkReportUserStatisicPojo pojo = iterator.next();
                    if (!execUserIds.contains(pojo.getUserId())) {
                        iterator.remove();
                    }
                }
            }

            LOGGER.error("SsExecutorServiceImpl:getWorkReportExecutorList:unDoneUsers:" + JSON.toJSONString(unDoneUsers));
            if (!unDoneUsers.isEmpty()) {
                List<String> userIds = new ArrayList<>();
                List<UserEntity> userList = new ArrayList<>();
                for (WorkReportUserStatisicPojo pojo : unDoneUsers) {
                    // 员工ids
                    userIds.add(pojo.getUserId());

                    // 员工实体
                    UserEntity userEntity = new UserEntity();
                    userEntity.setCorpid(corpid);
                    userEntity.setUserId(pojo.getUserId());
                    userEntity.setName(pojo.getUserName());
                    userEntity.setAvatar(pojo.getUserAvatar());
                    userList.add(userEntity);
                }


                // 拼接执行人数据
                SsExecutorPojo pojo = new SsExecutorPojo();
                pojo.setSmartSettingsId(aiAssistantEntity.getId());
                pojo.setFormId(aiAssistantEntity.getFormId());
                pojo.setExecutorIdList(userIds);
                pojo.setExecutorList(userList);
                ssExecutorList.add(pojo);
            }
        } catch (Exception e) {
            LOGGER.error("WorkReportAiAssistantStrategyHandle.getExecutorUserList 获取执行人失败：", e);
        }
        return ssExecutorList;
    }

    @Override
    public void sendDingTalkMessage(AiAssistantEntity aiAssistantEntity, List<SsMessageMergePojo> messageMergeList,
                                    List<AiAssistantHistoryEntity> addList, List<AiAssistantHistoryEntity> updateList,
                                    List<PaasFormDataEntityExt> dataList, RunStrategyDTO runStrategyDTO) {
        if (CollectionsUtil.isEmpty(messageMergeList)) {
            return;
        }
        String corpid = aiAssistantEntity.getCorpid();

        // 发送时间
        String sendTimeStr = getStrategyTime(aiAssistantEntity);
        Long sendTime = DateTimeUtil.getInt(sendTimeStr, DateTimeUtil.SDFYMDHM);
        // 添加消息
        for (SsMessageMergePojo userEntity : messageMergeList) {
            String title = XbbRefTypeEnum.AI_ASSISTANT.getName() + PaasConstant.COLON + aiAssistantEntity.getName();
            // 占位符的修改
            String placeHolder = smartSettingsHelp.getPlaceHolder(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_REPORT.getCode());
            // content内容
            String content = aiAssistantEntity.getMemo();
            content = content.replaceAll("\\{" + placeHolder + "\\}", "");
            // 测试时使用
            PushRefTypePojo.Options options = new PushRefTypePojo.Options(aiAssistantEntity.getAppId(), aiAssistantEntity.getMenuId(), aiAssistantEntity.getFormId(),
                    0L, aiAssistantEntity.getSaasMark(), XbbRefTypeEnum.WORK_REPORT.getCode(), XbbRefTypeEnum.WORK_REPORT.getCode());

            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(userEntity.getExcutorId()), Collections.singletonList(0L), 0,
                    sendTime, title, content, null, options);
            try {

                aiAssistantBaseProducer.sendMessage(AiAssistantPushTypeEnum.WORK_REPORT_PUSH, messageRabbitMqDTO);

            } catch (XbbException e) {
                LOGGER.error("WorkReportAiAssistantStrategyHandle.workReportSendDingTalkMessage", e);
            }
        }
        // TODO 未记录策略执行历史记录
    }

    @Override
    public void executionStrategy(SmartStrategyRabbitMqDTO rabbitMqDTO, RunStrategyDTO runStrategyDTO) {
        AiAssistantEntity aiAssistantEntity = rabbitMqDTO.getAiAssistantEntity();
        // 查询执行人，获取没写工作报告的人
        List<SsExecutorPojo> ssExecutorList = getExecutorUserList(aiAssistantEntity, new ArrayList<>(), new ArrayList<>());
        // 聚合
        List<SsMessageMergePojo>  ssMessageMergeList = ssMessageMergeService.getMessageMergeList(ssExecutorList, aiAssistantEntity, new ArrayList<>(), new ArrayList<>());
        // 执行动作
        SmartActionTypeEnum actionTypeEnum = SmartActionTypeEnum.getByCode(aiAssistantEntity.getAction());
        switch (actionTypeEnum) {
            case MESSAGE:
                // 走消息方法
                sendDingTalkMessage(aiAssistantEntity, ssMessageMergeList, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), runStrategyDTO);
                break;
            default:
                break;
        }
    }


}
